package com.example.teachingSystem.config;

import com.example.teachingSystem.utils.result.Result;
import com.example.teachingSystem.utils.result.ResultCodeEnum;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public <T> Result<T> exceptionHandler(Exception e){
        if(e instanceof SQLException){
            return Result.build(null, ResultCodeEnum.DATABASE_ERROR);
        }else if(e instanceof MethodArgumentNotValidException){
            List<ObjectError> allErrors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
            String message = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
            return  Result.build(null,500,message);
        }
        return Result.build(null, ResultCodeEnum.SYSTEM_ERROR);
    }
}
